<!-- 新增产品 -->
<template>
  <el-dialog
    custom-class="custom_dialog_box"
    title="新增产品"
    v-if="visible"
    :visible.sync="visible"
    width="780px"
    append-to-body
    destroy-on-close
    @close="dialogColse"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入产品名称"
              maxlength="30"
              :disabled="enterType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品系列" prop="seriesId">
            <!-- <el-select
              v-model="formData.seriesId"
              placeholder="请选择产品子系列"
            >
              <el-option
                v-for="item in allProductSeries"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select> -->
            <el-cascader
              v-model="formData.seriesId"
              placeholder="请选择产品子系列"
              :options="allProductSeries"
              :props="cascaderProps"
              clearable
              filterable
              :disabled="enterType === 'detail'"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="产品简介" prop="introduction">
        <el-input
          v-model="formData.introduction"
          type="textarea"
          placeholder="请输入产品简介"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 3, maxRows: 4 }"
          :disabled="enterType === 'detail'"
        />
      </el-form-item>

      <el-row>
        <el-form-item label="产品展示图" prop="picUrl">
          <el-upload
            :class="{
              'hide_upload': formData.picUrl,
              'hide_delete_icon': enterType === 'detail',
            }"
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.pic"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'picUrl')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'picUrl')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="产品方案图" prop="programmeUrl">
          <el-upload
            :class="{
              'hide_upload': formData.programmeUrl,
              'hide_delete_icon': enterType === 'detail',
            }"
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.programme"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'programmeUrl')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'programmeUrl')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-form-item label="产品介绍" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入产品介绍"
          maxlength="1000"
          show-word-limit
          :autosize="{ minRows: 4, maxRows: 6 }"
          :disabled="enterType === 'detail'"
        />
      </el-form-item>
    </el-form>

    <!-- 图片查看弹框 -->
    <el-dialog :visible.sync="imgDialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="dialogColse">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from "@/utils/auth";
import { UPLOADURL } from "@/api/useMenu/config";
import {
  productSave,
  productUpdate,
  productSeriesAllList,
  productSeriesList,
} from "@/api/useMenu/product";

export default {
  name: "AddProductDialog",
  data() {
    return {
      visible: false, // 弹框状态
      // 表单数据
      formData: {},
      // 校验
      rules: {
        name: [
          {
            required: true,
            message: "请输入产品名称",
            trigger: ["blur", "change"],
          },
        ],
        seriesId: [
          {
            required: true,
            message: "请选择产品系列",
            trigger: ["blur", "change"],
          },
        ],
        introduction: [
          {
            required: true,
            message: "请输入产品简介",
            trigger: ["blur", "change"],
          },
        ],
        picUrl: [
          {
            required: true,
            message: "请上传产品展示图",
            trigger: "change",
          },
        ],
        programmeUrl: [
          {
            required: true,
            message: "请上传产品方案图",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入产品介绍",
            trigger: ["blur", "change"],
          },
        ],
      },
      enterType: "", // 进入类型 add / edit /detail

      allProductSeries: [], // 系列列表

      // 上传参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + UPLOADURL,
      },

      // 图片回写
      picBackObj: {
        pic: [], //产品展示图
        programme: [], //产品方案图
      },

      cascaderProps: {
        emitPath: false,
        value: "id",
        label: "name",
        children: "seriesList",
      },

      // 图片详情弹框
      imgDialogVisible: false,
      dialogImageUrl: "",
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 打开弹框
    async openDialog(enterType = "add", item = {}) {
      this.visible = true;
      this.submitLoading = true;
      this.enterType = enterType;
      await this.getAllProductSeries();
      if (["edit", "detail"].includes(enterType)) {
        this.formData = { ...item };
        let { picUrl, programmeUrl } = item;
        let pic = this.dealwithImgBack(picUrl);
        let programme = this.dealwithImgBack(programmeUrl);
        this.picBackObj = { pic, programme };
        console.log("123");
      }
      this.submitLoading = false;
    },
    async getAllProductSeries() {
      // let res = await productSeriesAllList();
      let { rows } = await productSeriesList({
        pageNum: 1,
        pageSize: 9999,
        level: 1,
      });
      this.allProductSeries = [...rows];
    },

    dealwithImgBack(imgUrl) {
      let result = [];
      if (imgUrl) {
        let urlList = imgUrl.split(",");
        result = urlList.map(url => ({ url }));
      }
      return result;
    },
    // 上传成功
    handleAvatarSuccess(res, file, formKey) {
      let { msg } = res;
      let result = this.formData[formKey];
      if (result) {
        // 有值拼接
        result = result + "," + msg;
      } else {
        // 无值赋值
        result = msg;
      }
      this.$set(this.formData, formKey, result);
    },
    // 上传之前
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 20MB!");
      }
      return isLt2M;
    },
    handleRemove(file, fileList, formKey) {
      let urlList = fileList.map(item => item.response.msg);
      this.$set(this.formData, formKey, urlList.join(","));
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imgDialogVisible = true;
    },

    //  提交按钮
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          let { enterType, formData } = this;
          let request = enterType === "add" ? productSave : productUpdate;
          let { code, msg } = await request(formData);
          if (code === 200) {
            let msg = enterType === "add" ? "新增成功" : "修改成功";
            this.$modal.msgSuccess(msg);
            this.dialogColse();
            this.$emit("updateTable");
          } else {
            this.$modal.msgError(msg || "接口异常");
          }
          this.submitLoading = false;
        }
      });
    },
    // Dialog 关闭的回调
    dialogColse() {
      this.visible = false;
      this.formData = {};
      this.picBackObj = {
        pic: [], //产品展示图
        programme: [], //产品方案图
      };
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .custom_dialog_box {
  .el-dialog__body {
    max-height: 680px;
    overflow: auto;
  }
  .el-select {
    width: 100%;
  }
}
::v-deep .hide_upload {
  .el-upload {
    display: none !important;
  }
}

::v-deep .hide_delete_icon {
  .el-upload-list__item-delete {
    display: none !important;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
